package live.hotel.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;

import com.hotel.api.entity.HotelItem;
import com.hotel.api.entity.SearchHotelPriceRS;

import com.hotel.api.services.SearchHotelPriceService;
import com.hotel.api.utils.ConstEnum.PAYMENTTYPE;
import live.common.Format;
import live.common.Log4jXmlConfig;
import live.common.Page;
import live.hotel.entity.BaseHotel;
import live.hotel.entity.Search;

public class SearchHotelPrice{
	private Logger log = Log4jXmlConfig.getInstance().returnLogger(
			SearchHotelPrice.class);
	public SearchHotelPriceRS getHotelPriceInfos(Page page, Search query){
		SearchHotelPriceRS hotelPriceRs = null;
		try {
			SearchHotelPriceService service = new SearchHotelPriceService();
			String minPrice = query.getMinPrice()!=0?String.valueOf(query.getMinPrice()):"";
			String maxPrice = query.getMaxPrice()!=0?String.valueOf(query.getMaxPrice()):"";
			hotelPriceRs = (SearchHotelPriceRS)service.searchHotelPrice(page.getPageIndex(), page.getPageSize(), query.getCityCode(), PAYMENTTYPE.T, query.getHotelItem(), query.getCheckInDate(), returnDuration(query), query.getStarCode(), minPrice, maxPrice, query.getRgnLocation(), query.getBsnLocation(), query.getLngLocation());
		} catch (MarshalException e) {
			log.error(e.getMessage(),e);
		} catch (ValidationException e) {
			log.error(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		} catch (MappingException e) {
			log.error(e.getMessage(),e);
		}
		
		return hotelPriceRs;
	}
	
	public List<BaseHotel> getHotelPriceBase(Page page, Search query){
		SearchHotelPriceRS result = getHotelPriceInfos(page, query);
		List<BaseHotel> baseHotels = null;
		if(result.getErrors()==null&&Format.getInstance().isNotNullOrZeroForList(result.getItems())){
			BaseHotel item = null;
			baseHotels = new ArrayList<BaseHotel>();
			for (HotelItem hotelItem : result.getItems()) {
				item = new BaseHotel();
				item.setSalePrice(hotelItem.getRooms().get(0).getRates().get(0).getSalePrice());
				item.setHotelCode(hotelItem.getHotelCode());
				item.setHotelName(hotelItem.getHotelName());
				baseHotels.add(item);
				item=null;
			}
		}
		return baseHotels;
	}
	
	private int	returnDuration(Search search){
		String format="yyyy-MM-dd";
		Format formatPojo = Format.getInstance();
		Calendar calInDate = Calendar.getInstance();
		Calendar calOutDate = Calendar.getInstance();
		calInDate.setTime(formatPojo.stringToDate(search.getCheckInDate(), format));
		calOutDate.setTime(formatPojo.stringToDate(search.getCheckOutDate(), format));
		return (int)((calOutDate.getTimeInMillis()-calInDate.getTimeInMillis())/1000/60/60/24);
	}
}
